package com.syh.jn.scm.infrastructure.repository.impl.supplier.base;

import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.jn.scm.domain.supplier.entity.base.ProjectItem;
import com.syh.jn.scm.domain.supplier.repository.base.ProjectItemRepository;
import com.syh.jn.scm.dto.supplier.base.project.ProjectItemVo;
import com.syh.jn.scm.infrastructure.repository.model.base.ProjectItemModel;
import com.syh.jn.scm.infrastructure.repository.model.base.ProjectModel;
import com.syh.jn.scm.infrastructure.repository.model.base.goods.GoodsCategoryModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;

@Repository
public class ProjectItemRepositoryImpl extends AbstractAggregateRepository<ProjectItem, ProjectItemModel, Long> implements ProjectItemRepository {
  /**
   * 查找当前运营项目id的所有商品
   * @param projectId
   * @return
   */
  @Override
  public List<ProjectItem> findItemByProjectId(Long projectId) {
    Wrapper wrapper = Wrapper.build()
            .append(Restrictions.eq("projectId", projectId));
    List<ProjectItem> list = this.getList(wrapper);

    return list;
  }

  @Override
  protected SQL getViewSql() {
    return new SQL() {{
      SELECT(
              SQLAliasGenerateUtil.aliasGenerate(ProjectItemModel.class, "item", null),
              "project.NAME AS projectName",
              "project.CODE AS projectCode",
              "cate.NAME AS categoryName"
      );
      FROM(getModelTableName(ProjectItemModel.class)+" item");
      LEFT_OUTER_JOIN(
              getModelTableName(ProjectModel.class)+" project on item.PROJECT_ID = project.ID",
              getModelTableName(GoodsCategoryModel.class)+" cate on item.CATEGORY_ID = cate.ID"
      );
    }};
  }

  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    HashMap<String,String> weMap = new HashMap<>();
    weMap.put("id", "item.ID");
    weMap.put("name", "item.NAME");
    weMap.put("code", "item.GOODS_CODE");
    weMap.put("businessEntityId", "item.BUSINESS_ENTITY_ID");
    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return weMap.get(propertyName);
    });
    return parse;
  }

  @Override
  protected Class getViewObject() {
    return ProjectItemVo.class;
  }

}
